uniform sampler3D blocks;
uniform sampler3D colors;
uniform sampler2D textures;
varying vec3 pos;
varying float depth;
varying vec3 norm;
const vec3 light = vec3(0.267, 0.534, 0.802);

void main()
{
	vec4 data = texture3D(blocks, gl_TexCoord[1].zxy);

	if (data.g <= 0)
		discard;

	if (texture3D(blocks, gl_TexCoord[2].zxy).g > 0)
		discard;

	float block = floor(data.r * 256);
	vec2 btc = vec2(0.0, floor(block / 16.0) / 16.0);
	btc.x = floor(block - (16.0 * btc.y)) / 16.0;
	
	vec2 sub = vec2(0);

	if (norm.x != 0)
	{
		sub.x = 1.0 - fract(pos.y);
		sub.y = 1.0 - fract(pos.z);
	}
	else 
	{
		if (norm.y != 0)
		{
			sub = fract(pos.xz);
			sub.y = 1.0 - sub.y;
		}
		else 
		{
			sub = fract(pos.xy);
			sub.y = 1.0 - sub.y;
		}
	}

	sub *= 0.99;
	sub += vec2(0.005);
	
	vec4 texel = texture2D(textures, btc + gl_TexCoord[0].xy + sub / 32.0);
	float intense = (dot(norm, light) + 1) * 0.5;

	texel.rgb *= intense;
	texel.rgb = mix(texel.rgb, vec3(1), abs(depth) / 100.0);

	gl_FragColor = texel;
}
